﻿using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System.Collections;
using System.Collections.Generic;

public class Gamecontrol : MonoBehaviour 
{
    public delegate void EventHandler();

    private Character _player_leader = null;
    public event EventHandler e_leader_change;
    public Character player_leader{
        get{
            return _player_leader;
        }
        set{
            if (value != _player_leader) 
            {
                if (_player_leader != null) 
                {
                     _player_leader.leader = false;
                }
                value.leader = true;
                _player_leader = value;
                e_leader_change();
            }
        }
    }
    

    private bool _move_mode = true;                 //角色的行动模式
    public bool move_mode
    {
        get{
            return _move_mode;
        }
    }

    [Header("背包")]
    public GameObject bag;
    public GameObject item_perfab;
    public GameObject itemtips;
    public GameObject item_box_light;
    private List<GameObject> boxList = new List<GameObject>();

    [Header("技能")]
    public GameObject skill_effect_perfab;

    private AsyncOperation load;
    public EventHandler e_startgame;
    public EventHandler e_Dungeon_Created;
    private bool gamestart = false;

    [Header("点击移动")]
    [SerializeField]
    private LayerMask layermask;
    [HideInInspector]
    public Vector3 Moving_direction;                //即将移动方向

    public GameObject way_perfab;

    protected static Gamecontrol instance;
    public static Gamecontrol Instance
    {
        get
        {
            if (instance == null)
            {
                instance = (Gamecontrol)FindObjectOfType(typeof(Gamecontrol));
            }
 
            return instance;
        }
    }

    // public bool get_move_mode()
    // {
    //     return Queue_mode;
    // }
    public void set_move_mode()
    {
        _move_mode = !_move_mode;
    }

#region Scene_Manager
    public Scene_note root_note;
    public Scene_note now_note;
    public List<Scene_note> open_list;
    public List<Scene_note> close_list;
    private IEnumerator _loadScene(string name)
    {
        load = SceneManager.LoadSceneAsync(name,LoadSceneMode.Additive);
        yield return load;
    }
    public void startgame(string name)
    {
        StartCoroutine(_loadScene(name));
        Scene Tmp = SceneManager.GetSceneAt(SceneManager.sceneCount-1);
        if (!Tmp.isLoaded)
        {
            e_startgame();
            gamestart = true;
        }
    }
    public bool add_scene(Scene_note scene_note)
    {
        StartCoroutine(_loadScene(scene_note.name));
        //调整场景位置
        //刷新寻路信息
        //
        return true;
    }
    private void scene_loaded(Scene scene,LoadSceneMode mode)
    {
        
    }


#endregion //Scene_Manager

#region dungeon
    public Dungenon CurrDungenon;
    public int GetSeed()
    {
        return 500;
    }

    public void startgame()
    {
        if(CurrDungenon != null)
        {

        }
        Dungenon dungenon = new Dungenon(50, 50, 500, GetSeed());
        //StartCoroutine( CreateSceneByDungenon(dungenon, new Vector3(0f,0f,0f)) );
        CurrDungenon = dungenon;
        CreateSceneByDungenon(dungenon, new Vector3(0f,0f,0f));
        e_startgame();
        e_Dungeon_Created();
        gamestart = true;
    }
    
    public void CreateSceneByDungenon(Dungenon map, Vector3 pos)
    {
        GameObject obj;
        GameObject root = new GameObject("Scene");
        float height;
        Scene dungeon = SceneManager.CreateScene("dungeon");
        SceneManager.MoveGameObjectToScene(root,dungeon);
        // for(int i = map.wayNoteList.Count-1; i >= 0 ; i--)
        // {
        //     obj = Instantiate(way_perfab);
        //     SceneManager.MoveGameObjectToScene(obj, dungeon);
        //     obj.transform.position = pos + new Vector3(map.wayNoteList[i].x*Map.noteSize, 0f, map.wayNoteList[i].y*Map.noteSize);
        // }
        for (int i = 0; i < map.map.GetLength(1); i++)
        {
            for (int j = 0; j < map.map.GetLength(0); j++)
            {
                if(map.map[i,j].type != MapNoteType.nothing)
                {
                    if(map.map[i,j].type == MapNoteType.room)
                    {
                        height = 1f;
                    }
                    else
                    {
                        height = 0f;
                    }
                    obj = Instantiate(way_perfab);
                    SceneManager.MoveGameObjectToScene(obj, dungeon);
                    obj.transform.SetParent(root.transform);
                    obj.transform.position = pos + new Vector3(map.map[i,j].x*Dungenon.noteSize, height, map.map[i,j].y*Dungenon.noteSize);
                    //yield return 0;
                }
            }
        }
    }
#endregion


#region bag
    public void ini_bag_order()
    {
        GameObject[] boxes = GameObject.FindGameObjectsWithTag("item_box");
        //包裹格子作简单排序，顺序为从左上起逐行至右下格子
        boxList.AddRange(boxes);
        //boxList.Reverse(); //反序
        boxList.Sort(delegate(GameObject x, GameObject y)
        {
            Vector3 xp = x.transform.position;
            Vector3 yp = y.transform.position;
            if (xp.y == yp.y && xp.x == yp.x)
            {
                return 0;
            }
            if (xp.y==yp.y)
            {
                if (xp.x<yp.x)
                {
                    return -1;
                }
                return 1;
            }
            if (xp.x==yp.x)
            {
                if (xp.y>yp.y)
                {
                    return -1;
                }
                return 1;
            }
            if (xp.y>yp.y)
            {
                return -1;
            }
            return 1;
        });
        bag.SetActive(false);
        itemtips.SetActive(false);
    }

    public void change_bag_active()
    {
        bag.SetActive(!bag.activeSelf);
        itemtips.SetActive(false);
        item_box_light.SetActive(false);
    }

    public int add_item(int item_ID,int num)
    {
        int back = num;
        Item_box box;
        for (int k = 0; k < boxList.Count; k++) 
        {
            box = (Item_box)boxList[k].GetComponent<Item_box>();
            if ( box.item_ID == 0 || box.item_ID == item_ID) 
            {
                //int i = box.max_num - box.num;
                int i = 20 - box.num;
                if ( i > 0) 
                {

                    box.item_ID = item_ID;
                    if (i >= back) 
                    {
                        box.num += back;
                        Refresh_bag(boxList[k]);
                        return num;  
                    }
                    else
                    {
                        box.num += i;
                        back = back - i;   
                    }
                    Refresh_bag(boxList[k]); 
                }
            }
        }
        return num - back;
    }

    public void Refresh_bag(GameObject key)
    {
        Item_box box = (Item_box)key.GetComponent<Item_box>();
        if (box.item == null) 
        {
            box.item = Instantiate(item_perfab) as GameObject;
            box.item.transform.SetParent(bag.transform,false);
            box.item.GetComponent<Item>().Ini(key);
        }
        box.item.GetComponent<Item>().Refresh_num(box.num);
    }
#endregion //bag

    public GameObject Get_skill_effect(int id)
    {
        return Instantiate(skill_effect_perfab);
    }

   
    

    public void Test()
    {
        int num,id;
        num = Random.Range(1,25);
        id = Random.Range(10001,10019);
        Debug.Log("添加物品:id = " + id + "(" + add_item(id,num) + "/" + num );
    }
    void Awake () 
    {
        _player_leader = null;   
    }
    // Use this for initialization
    void Start ()
    {
        ini_bag_order();
        SceneManager.sceneLoaded += scene_loaded;
    }
    
    // Update is called once per frame
    void Update ()
    {
        if (!gamestart) 
        {
            return;
        }
        if(Input.GetButtonUp("Bag"))
        {
            change_bag_active();
        }
        if(Input.GetButtonUp("Switch_mode"))
        {
            set_move_mode();
        }
        // Moving_direction.Set( Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical") );
        // Moving_direction = Quaternion.Euler(0, 45, 0) * Moving_direction;  
        // Moving_direction.Normalize();
        //按下鼠标右键时
        if(Input.GetMouseButton(1))
        {
             //获取屏幕坐标
             Vector3 mScreenPos=Input.mousePosition;
             //定义射线
             Ray mRay=Camera.main.ScreenPointToRay(mScreenPos);
             Debug.DrawRay (mRay.origin, mRay.direction * 10, Color.yellow);
             RaycastHit mHit;
             //判断射线是否击中地面
            if(Physics.Raycast(mRay,out mHit, Mathf.Infinity, layermask.value))
            {
                // if(mHit.collider.gameObject.tag=="floor")
                // {
                    //获取目标坐标
                    Moving_direction = mHit.point;
                    //Debug.Log(Moving_direction);
                // }
            }
        }
        else {
            Moving_direction = Vector3.zero;
        }
    }

    void FixedUpdate()
    {
        
    }
}
